package com.sailors.common.task.provider.infra.design.common.enums;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Bussiness base enum util
 *
 * @description:
 * @author: cyj
 * @date 2022 -09-15 16:08:37
 */
@Slf4j
public class BussinessBaseEnumUtil {

    /**
     * Gets by code *
     *
     * @param <T>       parameter
     * @param code      code
     * @param enumClass enum class
     * @return the by code
     */
    public static <T extends BussinessBaseEnum> T getByCode(Integer code, Class<T> enumClass) {
        Map<Integer, T> collect = Arrays.stream(enumClass.getEnumConstants()).collect(Collectors.toMap(T::getCode, Function.identity()));
        return collect.get(code);
    }

    /**
     * Gets by text *
     *
     * @param <T>       parameter
     * @param text      text
     * @param enumClass enum class
     * @return the by text
     */
    public static <T extends BussinessBaseEnum> T getByText(String text, Class<T> enumClass) {
        Map<String, T> collect = Arrays.stream(enumClass.getEnumConstants()).collect(Collectors.toMap(T::getDesc, Function.identity()));
        return collect.get(text);
    }

    /**
     * Code to text string
     *
     * @param <T>       parameter
     * @param code      code
     * @param enumClass enum class
     * @return the string
     */
    public static <T extends BussinessBaseEnum>  String codeToText(Integer code, Class<T> enumClass){
        T t = getByCode(code, enumClass);
        return Optional.ofNullable(t).map(BussinessBaseEnum::getDesc).orElse(null);
    }

    /**
     * Text to code integer
     *
     * @param <T>       parameter
     * @param text      text
     * @param enumClass enum class
     * @return the integer
     */
    public static <T extends BussinessBaseEnum>  Integer textToCode(String text, Class<T> enumClass){
        T t = getByText(text, enumClass);
        return Optional.ofNullable(t).map(BussinessBaseEnum::getCode).orElse(null);
    }
}
